package com.bruce.learnrecycler.kotlin.store

import android.os.Bundle
import com.bruce.learnrecycler.kotlin.ui.listitem.Item
import com.bruce.learnrecylerview.app.action.MainActions
import com.github.bluzwang.fluxsupportkotlin.*
import com.github.bluzwong.flux.compiler.annotation.Maintain
import com.github.bluzwong.kotlin_x_weapon.runDelayedOnUiThread
import java.io.Serializable
import java.util.*
import javax.inject.Inject

/**
 * Created by wangzhijie@wind-mobi.com on 2015/9/2.
 */
public class MainStore Inject constructor(val disptch: Dispatcher) : Store(disptch) {


    override fun onDataRestored(savedData: SavedData) {
//        val saved = savedData.get("items")
//        items.clear()
//        items.addAll(saved as List<Item>)
        this responseToUIWithType MainActions.UI_ADD_ONE_ITEM key MainActions.KEY_ITEM_INDEX toValue 0 post null
    }

    Remain
    Maintain
    val items:MutableList<Item> = ArrayList<Item>()

    override fun onRequestDone(type:String, dataMap:Map<String, Any>) {
        when (type) {
            MainActions.SHOW_PD_BUS, MainActions.SHOW_PX_BUS -> {
                var item = dataMap.get(MainActions.KEY_RESULT_ITEM) as Item
                var index = dataMap.get(MainActions.KEY_ITEM_INDEX) as Int
                if (index > items.size()|| index == -2) {
                    index = items.lastIndex
                }
                if (index < 0) {
                    index = 0
                }
                items.add(index, item)
                runDelayedOnUiThread(1800) {
                    this responseToUIWithType MainActions.UI_ADD_ONE_ITEM key MainActions.KEY_ITEM_INDEX toValue index post null
                }
            }
        }
    }

    public fun requestRemoveItem(index: Int) {
        items remove index
        (this responseToUIWithType MainActions.UI_REMOVE_ONE_ITEM
                key MainActions.KEY_ITEM_INDEX toValue index
                post null)
    }

    public fun requestSwapItem(from: Int, to: Int) {
        Collections.swap(items, from, to)
        (this responseToUIWithType MainActions.UI_SWAP_ONE_ITEM
                key MainActions.KEY_ITEM_INDEX toValue from
                key MainActions.KEY_ITEM_INDEX2 toValue to
                post null)
    }

    override fun responseToUIWithType(type:String): Dispatcher.ResponseBuilder
            = super.responseToUIWithType(type) key MainActions.KEY_DATAS toValue ArrayList<Item>(items)

}